package pattern.structure.proxy.dynamic.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author : Rookie
 * @description : cglib动态代理
 * @date : 2023/10/2
 */
public class CglibDynamicProxy {

    public static void main(String[] args) {
        Calculate calculate = new Calculate();
        Calculate proxyInstance = (Calculate) new CglibProxy(calculate).getProxyInstance();

        System.out.println("原始类的类名：" + calculate.getClass().getName());
        System.out.println("代理类类名：" + proxyInstance.getClass().getName());
        proxyInstance.add(1,2);
    }
}

class Calculate {

    int add(int x,int y) {
        System.out.println("执行具体业务");
        return x+y;
    }
}

class CglibProxy implements MethodInterceptor {
    /**
     * 被代理类
     */
    private final Object obj;

    public CglibProxy(Object obj) {
        this.obj = obj;
    }

    /**
     * 获取被代理的对象
     * @return
     */
    public Object getProxyInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.obj.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib动态代理开始");
        Object invoke = method.invoke(this.obj, objects);
        System.out.println("cglib动态代理结束");
        return invoke;
    }
}
